package com.boesch.electroOffice.dataaccess.mapper;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.boesch.electroOffice.dataaccess.common.IllegalDataAccessException;
import com.boesch.electroOffice.dataaccess.dao.IdentifierDao;
import com.boesch.electroOffice.model.electroOffice.EldasArticle;
import com.boesch.electroOffice.utils.DateUtils;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

/**
 * This class mappes the rows from electroOffice database (Table e_eldas) to a article object.
 * 
 * @author Ralph Koster
 *
 */
public class EldasArticleMapper implements RowMapper<EldasArticle>, Serializable {

	private static final long serialVersionUID = -2881287826836898930L;
	private static final Log log = LogFactoryUtil.getLog(EldasArticleMapper.class);

	private IdentifierDao identifierDao;

	public EldasArticleMapper(IdentifierDao identifierDao) {
		this.identifierDao = identifierDao;
	}

	/**
	 * Mapps all rows from electroOffice database (Table e_eldas) to a article object.
	 * 
	 * @see org.springframework.jdbc.core.RowMapper
	 */
	public EldasArticle mapRow(ResultSet rs, int rowNum) throws SQLException {
		EldasArticle article = new EldasArticle();
		try {
			article.setId(rs.getInt("Id_pk"));
			article.setENumber(rs.getInt("ENumber"));
			article.setDescription(rs.getString("Description"));
			article.setQuantity(rs.getDouble("Quantity"));
			article.setUom(rs.getString("Uom"));
			article.setAppointmentId(rs.getInt("AppointmentId"));
			article.setMaterialIdentifier(identifierDao.getIdentifierById(rs.getInt("MaterialIdentifierId")));
			article.setCreatedBy(rs.getString("Createdby"));
			article.setCreatedAt(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Createdat")));
			article.setModifiedBy(rs.getString("Modifiedby"));
			article.setModifiedAt(DateUtils.convertTimestampToLocalDateTime(rs.getTimestamp("Modifiedat")));
			article.setVersion(rs.getInt("Version"));
		} catch (IllegalDataAccessException e) {
			log.error("Failed to load identifier with id: " + rs.getInt("ToolIdentifierId"), e);
			throw new SQLException("Failed to load identifier!", e);
		}
		return article;
	}
}
